<?php

/**
 * This is the model class for table "FlatCategory".
 *
 * The followings are the available columns in table 'FlatCategory':
 * @property integer $id
 * @property integer $low
 * @property integer $high
 * @property string $name
 * @property integer $block_id
 */
class FlatCategory extends ActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return FlatCategory the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'FlatCategory';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {

        return array(
                array('name, block_id', 'required'),
                array('low, high, block_id', 'numerical', 'integerOnly'=>true),
                array('name', 'length', 'max'=>255),
                array('low', 'compare', 'allowEmpty'=>false, 'compareValue'=>0, operator => '>=', 'message'=> 'Az alsó határ legalább 0 kell legyen.'),
                array('low', 'default', 'value'=>0 ),
                array('high', 'compare', 'allowEmpty'=>true, 'compareAttribute'=>'low', 'operator'=> '>', 'message'=> 'Nagyobb kell legyen mint az alsó határ.'),
                array('high', 'compare', 'allowEmpty'=>true, 'compareValue'=>1000, 'operator' => '<=', 'message'=> 'A felső határ legfeljebb 1000.'),
                array('low', 'noOverlapping'),

                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('id, low, high, name, block_id', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        return array(
                'block' => array(self::BELONGS_TO, 'Block', 'block_id'),
        );
    }

    public function byBlock($block)
    {
        $blockId = ($block instanceof Block) ? $block->id : $block;

        $this->getDbCriteria()->mergeWith(array(
                'condition' => 'block_id = :blockId',
                'params'=>array(':blockId'=> $blockId)
        ));

        return $this;
    }

    /**
     *
     * @param string $attribute name of attribute to validate
     * @param array $params pameters
     */
    public function noOverlapping($attribute, $params){

        // assemble criteria
        $criteria = new CDbCriteria();

        if(!$this->isNewRecord){
            $criteria->addCondition('id <> :thisid');
        }

        $criteria->params = array(
                ':thisid'=> $this->id,
                ':lowValue'=> $this->low );

        if(null == $this->high){

            $criteria->addCondition('
                    ( t.high IS NOT NULL AND t.high >= :lowValue )
                     OR
                    ( t.high IS NULL AND t.low >= :lowValue ) ');

        }else{

            $criteria->addCondition('
                    ( t.high IS NULL AND t.low <= :highValue )
                    OR
                    ( t.high IS NOT NULL AND
                        (( :lowValue BETWEEN t.low AND t.high)
                        OR
                        ( :highValue BETWEEN t.low AND t.high)
                        OR
                        ( t.high BETWEEN :lowValue AND :highValue )
                        OR
                        ( t.low BETWEEN :lowValue AND :highValue ))
                    ) ');

            $criteria->params[':highValue'] = $this->high;

        }


        // search conflicted categories
        $isConflict = self::byBlock($this->block_id)->exists($criteria);

        if($isConflict){
            $this->addError('low', 'A határok nem lehetnek átfedésben már meglévő kategóriákkal.');
            $this->addError('high', 'A határok nem lehetnek átfedésben már meglévő kategóriákkal.');
        }


    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
                'id' => 'ID',
                'low' => 'Alsó határ',
                'high' => 'Felső határ',
                'name' => 'Név',
                'block_id' => 'Háztömb',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {

        $criteria=new CDbCriteria;

        $criteria->compare('low',$this->low);
        $criteria->compare('high',$this->high);
        $criteria->compare('name',$this->name,true);

        return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
                'sort'=>array(
                        'defaultOrder'=>'low ASC',
                )
        ));
    }
}